package com.googlecode.quillen.util;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

/**
 * Created by IntelliJ IDEA.
 * User: greg
 * Date: Apr 12, 2009
 * Time: 4:56:41 PM
 */
public class TempFileUtils
{
    private static final String PREFIX = "quillen_" + System.currentTimeMillis() + "_" + RandomUtils.nextInt() + "_";
    private static final Object LOCK = new Object();
    private static int SEQ_NUM = 0;

    static
    {
        Runtime.getRuntime().addShutdownHook(new Thread()
        {
            public void run()
            {
                deleteAll(PREFIX);
            }
        });
    }

    public static String getPrefix()
    {
        synchronized(LOCK)
        {
            return PREFIX + "_" + SEQ_NUM++ + "_";
        }
    }

    public static void deleteAll(String prefix)
    {
        Iterator iter = FileUtils.iterateFiles(SystemUtils.getJavaIoTmpDir(), FileFilterUtils.prefixFileFilter(prefix), FileFilterUtils.directoryFileFilter());
        while (iter.hasNext())
        {
            FileUtils.deleteQuietly((File) iter.next());
        }
    }

    public static File createTempFile(String prefix) throws IOException
    {
        return File.createTempFile(prefix, null);
    }
}
